package com.xingfei.blog.service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.xingfei.blog.dto.UserDTO;
import com.xingfei.blog.redisCluster.RedisClusterUtil;
import com.xingfei.blog.vo.UserInfoVO;
import com.xingfei.blog.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 通过邮件访问网址（不同浏览器直接不能获取cookie）
 * Created by yhang on 2017/6/14.
 */
@Service("webEmailService")
public class WebEmailService {

    @Autowired
    private WebUserService webUserService;
    @Autowired
    private WebPersonalService webPersonalService;
    @Autowired
    private RedisClusterUtil redisCluster;

    private static String Profix_Email = "email:";

    /*
    个人中心邮件确认
     */
    public boolean checkEmailCode(String token) {
        //根据token获取用户信息
        if(StringUtils.isNotEmpty(token)){
            UserVO user = webUserService.getUser4Redis(token);
            //获取邮箱
            String email = redisCluster.get(Profix_Email + token);
            //清空邮件缓存
            redisCluster.del(Profix_Email + token);
            if(user!=null && StringUtils.isNotEmpty(email)){
                UserDTO userDTO = new UserDTO();
                userDTO.setId(user.getId());
                userDTO.setEmail(email);
                boolean b = webPersonalService.updateUserEmail(userDTO);
                if(b){
                    //更新redis
                    user.setEmail(email);
                    UserInfoVO userInfoVO = user.getUserInfoVO();
                    userInfoVO.setEmail(email);
                    user.setUserInfoVO(userInfoVO);
                    webPersonalService.updateRedis(token, user);
                    return true;
                }
            }
        }
        return false;
    }

    public void firstToLoad(HttpServletRequest request,UserVO userVO) {
        //加载数据
        this.webUserService.firstToLoad2(request,userVO);
    }
}
